﻿using Assets.Scripts.DL.Enemy.CommonEnemy;
using Assets.Scripts.DL.Mgrs;
using UnityEngine;

namespace Assets.Scripts.DL.Enemy.FlyEnemy {
	public class FlyDash : CommonState<Controller> {
		readonly Timer _timer;
		bool _sendDamage;
		readonly float _range;
		readonly int _damage;
		readonly Timer _dashTimer = new();

		public FlyDash(Controller controller, StateEnum stateName) : base(controller, stateName) {
			_timer = _controller.StateData.AtkCdRecoder[StateEnum.Atk2];

			AddConditionToSelf(() => _timer.Elapsed > _controller.Config.CommonAtkGap && _controller.IsPlayerInAtkRange());
			_range = _controller.Config.AtkDis;
			_damage = _controller.Config.Damage;
		}

		public override void Enter() {
			_controller.PlayAnim(StateName);
			var playerPos = _controller.GetPlayerPos();
			_controller.StateData.AtkOver = false;
			var targetPos = new Vector2(playerPos.x, playerPos.y);
			Vector2 curPos = _controller.transform.position;
			var dir = (targetPos - curPos).normalized;
			_controller.Velocity = dir * _controller.Config.FlyDashSpeed;
			_sendDamage = false;

			var faceDir = dir.x > 0 ? 1 : -1;
			ChangeFaceDir(faceDir);
			_dashTimer.Reset();
		}
		public override void Update() {
			if (_dashTimer.Elapsed > _controller.Config.DashTime) {
				//Debug.Log(_dashTimer.Elapsed);
				_controller.StateData.AtkOver = true;
			}
			else if (IsTouchPlayer() && !_sendDamage) {
				_controller.CheckAtk(Vector2.zero, _range, _damage);
				//ScreenEffectMgr.Instance.CutEffect(_controller.GetPlayerPos(), 45);
				_sendDamage = true;
			}
		}

		public override void Exit() {
			_timer.Reset();
			_controller.StateData.LastAtkTime.Reset();
			_controller.Velocity = Vector2.zero;
		}

		bool IsTouchPlayer()
			=> null != Physics2D.OverlapCircle(_controller.transform.position, _range, 1 << LayerMask.NameToLayer(LayerStrings.Player));

		void ChangeFaceDir(int faceDir)
		=> _controller.transform.localScale = new Vector3(faceDir, 1, 1);
	}
}
